package com.bbs.toutiao.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;

import cn.hutool.jwt.JWTValidator;
import com.bbs.toutiao.entity.UserEntity;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;


/**
 * 描述: 生成token 验证有效性
 * 作者： zhangBin
 * 时间： 2023/9/17 14:20
 * 版本： 1.0
 */

@Slf4j
public class Jwt {
    public static String KEY = "ZHANG";

    public static String getToken(UserEntity userEntity) {
        final LocalDateTime localDateTime = LocalDateTimeUtil.now();
        //默认令牌过期时间7天
        LocalDateTime offset = LocalDateTimeUtil.offset(localDateTime, 4, ChronoUnit.DAYS);
        System.out.println(DateUtil.date(offset));
//        setExpiresAt 过期时间 setNotBefore 派发时间
        return JWT.create()
                .setNotBefore(DateUtil.date())
                .setExpiresAt(DateUtil.date(offset))
                .setIssuedAt(DateUtil.date())
                .setPayload("userId", userEntity.getId())
                .setPayload("user_account", userEntity.getAccount())
                .setKey(KEY.getBytes())
                .sign();
    }

    //判断Token 是否有效
    public static Boolean verify(String token) {
        JWT jwt;
        boolean verify;
        try {
            Assert.notBlank(token);    //token不能为空
            jwt = JWT.of(token);
            jwt.verify();
            verify = JWTUtil.verify(token, KEY.getBytes());
            JWTValidator.of(token).validateDate(DateUtil.date());
        } catch (JWTException e) {
            log.error("您的token格式有误");
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        } catch (IllegalArgumentException e) {
            log.error("token不能为空" + e.getMessage());
            throw new BaseException(ExceptionEnum.TOKEN_NOT_NULL);
        } catch (ValidateException e) {
            log.error("token过期" + e);
            throw new BaseException(ExceptionEnum.TOKEN_TIME_OUT);
        } catch (JSONException e) {
            log.error("token格式错误" + e.getMessage());
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        return verify;
    }

}
